//###############
//FILE : UserThread.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############
package oop.ex3.filemanager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;


/**
 * This thread waits for user input and uses it to execute a command.
 * It's initialized with a list of commands that it can execute. After getting
 * input it checks if one of them matches the current input and if so, executes it.
 * @author daniel
 */
public class UserThread extends Thread{
	private static final String COMMAND_ERROR = "Invalid Command";
    ArrayList<UserCommand> _userCommands;

    /**
     * Iniitlize a user thread.
     */
    public UserThread() {
        _userCommands = new ArrayList<UserCommand>();
    }


    /**
     * Add a command to the list of recognized commands.
     * @param command The command to add.
     */
    public void addCommand(UserCommand command) {
        _userCommands.add(command);
    }

    @Override
    public void run() {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
		boolean stayAlive = true;

		while (stayAlive) {
            try {

                String input = bufferedReader.readLine().trim();

                //look for the right command
                boolean foundCommand = false;
                for (UserCommand command : _userCommands) {

                    if (command.recognizeCommand(input)) {
                        stayAlive = command.executeCommand(input);
                        foundCommand = true;
                        break;
                    }
                }
                
                
                //if no command was found
                if (!foundCommand) {
                	System.out.println(COMMAND_ERROR);
                }

            } catch (IOException ex) {
                //there's no reason that we shouldn't be able to read from standard input.
                ex.printStackTrace();
            }
            }
    }
}
